package com.cloud.service.impl.imports;

import cn.hutool.core.date.DatePattern;
import cn.hutool.json.JSONUtil;
import com.cloud.comm.CommonContext;
import com.cloud.enums.SupportImportMovieEnum;
import com.cloud.mq.topic.RabbitmqConfig;
import com.cloud.pojo.movie.ImportMovie;
import com.cloud.service.ImportMovieService;
import com.cloud.util.FileUtils;
import com.cloud.util.ThreadUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

/**
 * @version v1.0
 * @author: TianXiang
 * @description: url导入
 * @date: 2020/11/24
 */
public class ImportMovieURLServiceImpl implements ImportMovieService {
    private static final Logger LOG = LoggerFactory.getLogger(ImportMovieURLServiceImpl.class.getName());

    @Override
    public void importMovie(ImportMovie importMovie, MultipartFile file, RabbitTemplate rabbitTemplate, RedisTemplate<String,String> redisTemplate) {
        if(null == file
                && SupportImportMovieEnum.URL.getCode().equals(importMovie.getSupportFlag())
                && !StringUtils.isBlank(importMovie.getDownloadFromUrl())
                && !StringUtils.isBlank(importMovie.getMovieName())) {
            String moviesPath = CommonContext.getContext().getMoviesPath();
            String ffmpegExePath = CommonContext.getContext().getFfmpegExePath();
            ThreadUtils.executeTask(new Thread(() -> {
                String fileName = importMovie.getMovieName().trim().replaceAll(" ", "");
                if(fileName.lastIndexOf(".") == -1) fileName += ".mp4";
                if(this.cacheExistMoive(fileName.split("\\.")[0], redisTemplate)){
                    LOG.error("redis中存在该视频名称, 跳过此操作");
                    return;
                }
                importMovie.setMovieName(fileName)
                        .setDateDirName(DatePattern.PURE_DATE_FORMAT.format(new Date()))
                        .setDirName(UUID.randomUUID().toString().split("-")[0]);
                String uuidDirPath = moviesPath+ File.separator+ importMovie.getDateDirName()+ File.separator+ importMovie.getDirName();
                String movieFilePath = FileUtils.getMovieFilePath(fileName, uuidDirPath);
                File movieFile = null;
                try {
                    LOG.info("子线程下载url视频");
                    movieFile = new File(movieFilePath);
                    org.apache.commons.io.FileUtils.copyURLToFile(new URL(importMovie.getDownloadFromUrl()), movieFile);
                    LOG.info("子线程下载url视频完成");
                } catch (IOException e) {
                    LOG.error(e.toString());
                }
                if(null != movieFile && movieFile.exists()) {
                    importMovie.setUuidDirPath(uuidDirPath);
                    importMovie.setMovieFilePath(movieFilePath);
                    importMovie.setFfmpegExePath(ffmpegExePath);
                    // 异步消费
                    rabbitTemplate.convertAndSend(RabbitmqConfig.EXCHANGE_TOPICS, RabbitmqConfig.ROUTINGKEY_TRANSFER_MOVIE, JSONUtil.toJsonStr(importMovie));
                }else {
                    LOG.error("视频下载完成了, 但没推送到队列 原因 文件: {}" , movieFilePath);
                    if(null != movieFile) {
                        LOG.error("文件存在?: {}" , movieFile.exists());
                    }
                }
            }));
        }else {
            LOG.error("url导入失败: {}", JSONUtil.toJsonStr(importMovie));
        }
    }
}
